// pages/personal/index.ts
import { timeout } from "../../api/config";
import { save } from "../../api/reservation";
import {updateUser,UserDto} from "../../api/user"
import { LENGYU_SUCCESS_CODE } from "../../utils/request";

Page({

  /**
   * 页面的初始数据
   */
  data: {
      user:{} as UserDto,
      btnLoading:false,
      error:"",
      rules: [
        {
          name: 'name',
          rules: {required: true, message: '请填写姓名'},
        },
        {
          name: 'phone',
          rules: {required: true, message: '请填写手机号'},
        },
        {
          name: 'idCard',
          rules: {required: true, message: '请填写身份证号'},
        },
        {
          name: 'company',
          rules: {required: true, message: '请填写所属企业'},
        }
      ]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    this.init()

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },
// 首页返回按钮点击事件
  onBackClick: function() {
    wx.navigateTo({
      url: '../index?finish=true'
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  init(){
    let userStr =  wx.getStorageSync("user");
    let user1:UserDto = JSON.parse(userStr) as UserDto
    this.setData({
      "user":user1
    })
  },
  
  submitForm(){
    console.log("formvalid",this.data.user)
    this.selectComponent('#form').validate((valid:any, errors:any) => {
        console.log('valid结果', valid, errors)
        if (!valid) {
            const firstError = Object.keys(errors)
            if (firstError.length) {
                this.setData({
                    error: errors[firstError[0]].message
                })
            }
        } else {
            this.save()
        }
    })
  },

  async save(){
// console.log("提交表单：",this.data.user)
    this.setData({
      btnLoading:true
    })
    
    let res = await updateUser(this.data.user);
    if(res.code == LENGYU_SUCCESS_CODE){
      wx.setStorageSync("user",JSON.stringify(this.data.user))
      wx.navigateBack({
        delta: 1
      })
    }
    else{
      console.log("获取到了返回信息",res)
      this.setData({
        error:res.code + "  " +res.msg
      })
    }
    this.setData({
      btnLoading:false
    })
  },
  formInputChange(e:any){

    let field = e.currentTarget.dataset.field
    let value = e.detail.value
    this.setProperty("user",field,value);
  },
  setProperty(obj: string, key: string, value: any): void {
    const path = obj+"."+ key;
    this.setData({
      [path]:value
    })
  },
})